import { templateFile } from "@/api";
import { ContextMenu, ContextMenuItemProps } from "@/components";
import { ConfirmUtil, ResultUtil } from "@/util";
import { useStore } from "@/util/hooks";
import { Delete, Edit, FileAdditionOne } from "@icon-park/react";
import React, { PropsWithChildren } from "react";
import { TemplateFileTree, TemplateFileUtil, TemplateTreeAtom } from "..";
import { TemplateFileModalAtom } from "./modal-file";
import { TemplateRenameModalAtom } from "./rename-file";

export const TemplateFileContextMenu: React.FC<PropsWithChildren<any>> = ({
  children,
}) => {
  const treeStore = useStore(TemplateTreeAtom);
  const fileModalStore = useStore(TemplateFileModalAtom);
  const renameModalStore = useStore(TemplateRenameModalAtom);

  const { clickedKey, originData } = treeStore.value;
  const record = TemplateFileUtil.getFileRecord(clickedKey!, originData);

  function onAddFileClick() {
    fileModalStore.updateStore({
      open: true,
      directory: false,
    });
  }

  function onAddFolderClick() {
    fileModalStore.updateStore({
      open: true,
      directory: true,
    });
  }

  function onEditClick() {
    renameModalStore.updateStore({
      open: true,
      directory: true,
      record: record!,
    });
  }

  async function onRemoveClick() {
    const res = await templateFile.deleteFile(record!.path);
    if (ResultUtil.showResult(res)) {
      TemplateFileTree.init(treeStore);
    }
  }

  const menus: ContextMenuItemProps[] = [
    {
      key: "addFile",
      title: "新建文件",
      icon: <FileAdditionOne />,
      onClick: onAddFileClick,
      hidden: !!record && !record.directory,
    },
    {
      key: "addFolder",
      title: "新建文件夹",
      icon: <FileAdditionOne />,
      onClick: onAddFolderClick,
      hidden: !!record && !record.directory,
    },
    {
      key: "edit",
      title: "重命名",
      icon: <Edit />,
      hidden: !clickedKey,
      onClick: onEditClick,
    },
    {
      key: "delete",
      title: "删除",
      icon: <Delete />,
      hidden: !clickedKey,
      onClick: () => ConfirmUtil.removeConfirm(onRemoveClick),
    },
  ];

  return <ContextMenu menus={menus}>{children}</ContextMenu>;
};
